package cn.com.fuhuitong.main.home.ui.fragment

import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import cn.com.fuhuitong.app.BaseApplication
import cn.com.fuhuitong.entity.EmptyState
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.base.ViewModeFragment
import cn.com.fuhuitong.main.home.adapter.CharityListAdapter
import cn.com.fuhuitong.main.home.vm.CharityViewModel
import com.alibaba.android.vlayout.layout.LinearLayoutHelper
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.app.BASE_HTTP_URL
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.base.EmptyContent
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.entity.WebConfig
import cn.com.fuhuitong.main.ItemViewType
import cn.com.fuhuitong.main.home.adapter.CaseImageAdapter
import cn.com.fuhuitong.main.home.adapter.CaseVideoAdapter
import cn.com.fuhuitong.main.home.vm.CaseViewModel
import cn.com.fuhuitong.main.order.ui.fragment.OrderListFragment
import cn.com.fuhuitong.utils.JsonUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.tencent.smtt.sdk.TbsVideo
import kotlinx.android.synthetic.main.fragment_home_case.*
import kotlinx.android.synthetic.main.fragment_home_case.smartRefreshLayout
import kotlinx.android.synthetic.main.fragment_home_charity.*
import kotlinx.android.synthetic.main.fragment_order_list.*

class HomeCaseFragment : ViewModeFragment<CaseViewModel>() {

    companion object {
        private const val ACTION = "action"
        private const val TYPE = "type"
        fun newInstance(action: Int, type: Int): HomeCaseFragment {
            val fragment = HomeCaseFragment()
            fragment.arguments = Bundle().apply {
                putInt(ACTION, action)
                putInt(TYPE, type)
            }
            return fragment
        }
    }

    private lateinit var caseVideoAdapter: CaseVideoAdapter

    private lateinit var caseImageAdapter: CaseImageAdapter

    override fun viewModel(): CaseViewModel = ViewModelProvider(
        this, ViewModelProvider.AndroidViewModelFactory(BaseApplication.INSTANCE)
    ).get(CaseViewModel::class.java)

    override val layoutResId: Int
        get() = R.layout.fragment_home_case

    override fun initView() {

        this.initViewRecyclerAdapter(
            recycler_case_list, arrayOf(ItemViewType.CASE_LIST)
        )

        CaseVideoAdapter(
            requireContext(), LinearLayoutHelper().apply {
                setDividerHeight(resources.getDimensionPixelSize(R.dimen.dp_10))
            }
        ).apply { caseVideoAdapter = this }

        CaseImageAdapter(
            requireContext(), LinearLayoutHelper().apply {
                setDividerHeight(resources.getDimensionPixelSize(R.dimen.dp_10))
            }
        ).apply { caseImageAdapter = this }

        delegateAdapter.addAdapter(
            when {
                arguments?.getInt(TYPE) == 1 -> caseVideoAdapter
                arguments?.getInt(TYPE) == 2 -> caseImageAdapter
                else -> null
            }
        )

        caseVideoAdapter.setOnItemClickListener { view, i, caseEntity ->

            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
                .withSerializable(
                    AppConstance.BUNDLE_WEB_VIEW,
                    MainBean(type = WebConfig.UNKNOWN.apply {
                        desc = caseEntity.title
                    }, data = caseEntity.content)
                )
                .navigation()
        }

        caseVideoAdapter.setOnItemChildClickListener { view, i, caseEntity ->
            when (view.id) {
                R.id.text_case_list_video_play -> {
//                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
//                        .withSerializable(
//                            AppConstance.BUNDLE_WEB_VIEW,
//                            MainBean(type = WebConfig.UNKNOWN.apply {
//                                desc = caseEntity.title
//                            }, data = caseEntity.url)
//                        )
//                        .navigation()

                    if (TbsVideo.canUseTbsPlayer(requireActivity())) {
                        TbsVideo.openVideo(
                            requireActivity(),
                            "$BASE_HTTP_URL${caseEntity.file}",
                            Bundle().apply {
                                putInt("screenMode", 102)
                            })
                    }
                }
            }
        }

        caseImageAdapter.setOnItemClickListener { view, i, caseEntity ->

            ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_WEB_VIEW)
                .withSerializable(
                    AppConstance.BUNDLE_WEB_VIEW,
                    MainBean(type = WebConfig.UNKNOWN.apply {
                        desc = caseEntity.title
                    }, data = caseEntity.content)
                )
                .navigation()
        }

        /**
         * 1.强制客户登录设置
         * 2.版本更新
         * */


        with(smartRefreshLayout) {
            setRefreshHeader(MaterialHeader(requireContext()))
            setRefreshFooter(ClassicsFooter(requireContext()))
        }
        smartRefreshLayout.setOnRefreshListener {
            smartRefreshLayout.finishRefresh(true)
            //viewModel.caseIndex(arguments?.getInt(TYPE) ?: 0)
            initData()
        }
        smartRefreshLayout.setOnLoadMoreListener {
            smartRefreshLayout.finishLoadMore(true)
            //viewModel.caseIndex(arguments?.getInt(TYPE) ?: 0)
            initData()
        }

    }

    override fun initViewMode() {
        viewModel.caseListDataLiveData.observe(this, Observer { response ->

            val dataLength: Int = response.response?.data?.list?.size ?: 0

            smartRefreshLayout.isEnabled = dataLength != 0
            if (dataLength < 100) {
                smartRefreshLayout.finishLoadMoreWithNoMoreData()
            }

            when (response.status) {
                HttpResponseStatus.Status.START -> {
                    if (dataLength == 0) {
                        showLoadEmptyView()
                    }
                }
                HttpResponseStatus.Status.SUCCESS -> {
                    if (dataLength == 0) {
                        showNullEmptyView(EmptyContent("重新加载", "暂无数据"))
                    } else {
                        hideEmptyView()
                    }
                }
                HttpResponseStatus.Status.FAILURE -> {
                    if (dataLength == 0) {
                        showErrorEmptyView(EmptyContent("重新加载", response.statusTip))
                    }
                    toast(response.statusTip)
                }
            }

            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.list?.let {
                if (arguments?.getInt(TYPE) == 1) {
                    caseVideoAdapter.setAddDataNew(it)
                } else if (arguments?.getInt(TYPE) == 2) {
                    caseImageAdapter.setAddDataNew(it)
                }
            }
        })
    }

    override fun initData() {
        val action: Int = arguments?.getInt(ACTION) ?: 0
        if (action == 1) {
            viewModel.caseIndex(arguments?.getInt(TYPE) ?: 0)
        } else if (action == 2) {
            viewModel.caseChairIndex(arguments?.getInt(TYPE) ?: 0)
        }
    }

    override fun onLoadingEmptyView(state: EmptyState) {
        super.onLoadingEmptyView(state)
        //viewModel.caseIndex(arguments?.getInt(TYPE) ?: 0)
        initData()
    }

}